import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author Jimmy Zhan WORKSTATION
 * @date 2023/3/30 17:40
 * 说明：
 */

public class UDPTest {
    @Test
    public void sender() throws Exception{
        // 1. 创建DatagramSocket实例
        DatagramSocket ds = new DatagramSocket();

        // 3. DatagramPacket实例化时参数需要指定  数据、开始位置、长度、inetAddress、port
        int port = 9090;
        InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
        byte[] bytes = "我是发送端".getBytes(StandardCharsets.UTF_8);
        DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length, inetAddress, port);

        // 2. 发送数据，参数是packet，需要创建DatagramPacket的实例
        ds.send(packet);

        ds.close();
    }

    @Test
    public void receiver() throws IOException {
        // 1. 创建DatagramSocket的实例
        int port = 9090;
        DatagramSocket ds = new DatagramSocket(port);

        // 2. 创建数据报的对象，用于接收发送端发送过来的数据
        byte[] buffer = new byte[1024 * 64];

        DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);

        // 3. 接收数据
        ds.receive(packet);

        // 4. 获取数据并打印到控制台
        String str = new String(packet.getData(), 0, packet.getLength());
        System.out.println(str);
        ds.close();
    }
}
